package com.chain.qs.modules.biz.service;

import com.chain.qs.common.utils.EhCacheUtils;
import com.chain.qs.modules.biz.entity.Handover;
import com.chain.qs.modules.biz.entity.HandoverException;
import com.chain.qs.modules.biz.entity.HandoverInfo;
import com.chain.qs.common.schedule.QuartzJobBean;
import com.chain.qs.modules.sys.entity.User;
import com.chain.qs.modules.sys.utils.UserUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;

@Service("handoverTaskService")
public class HandoverTaskService extends JobOperationService{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

//    @Resource(name="schedulerFactoryBean")
//    private StdScheduler scheduler;

    @Resource
    private HandoverExceptionService handoverExceptionService;

    @Resource
    private HandoverInfoService handoverInfoService;

    @Resource
    private HandoverService handoverService;

    /**
     * 任务执行时间为：班次时间+，只要任务执行就表示有超时存在
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        QuartzJobBean scheduleJob = (QuartzJobBean)jobExecutionContext.getMergedJobDataMap().get("scheduleJob");
        //获取状态  0：正在值班   1：已交接班
        Object obj = EhCacheUtils.get(EhCacheUtils.HANDOVER_CACHE,scheduleJob.getJobName());
        int status = (obj==null)?0:(Integer)obj;
        if(status == 1){
            //已交班，恢复为值班状态
            EhCacheUtils.put(EhCacheUtils.HANDOVER_CACHE,scheduleJob.getJobName(),0);
            return ;
        }
        User user = UserUtils.getUser();
        //下面为未交班处理
        //检查这个任务是否已交接班
//        System.out.println(scheduleJob.getJobId()+" new test 打印日志看看一下中。"+scheduleJob.getJobName());
        //异常信息

        //查询执班信息
        HandoverInfo handoverInfo = handoverInfoService.getLastInfo(user);
        HandoverException handoverException = new HandoverException();
        handoverException.setProvider(handoverInfo.getSuccessor());
        handoverException.setSuccessor(new User());
//        handoverException.setExceptionReason(HandoverExceptionEnum.OVER_TIME);
        handoverException.setDate(new Date());
        handoverException.setExceptionReason("超时，未交接！");
        handoverException.setFlag(0); //异常未处理
        handoverExceptionService.save(handoverException);

//        handoverInfo.setFlag(1);//存在异常
//        handoverInfo.setException(handoverException.getId());
//        handoverInfoService.save(handoverInfo);

        //TODO 推送  当前班次内容
        Handover handover = handoverService.getHandover();

        EhCacheUtils.put(EhCacheUtils.HANDOVER_CACHE, EhCacheUtils.HANDOVER_CUR_CACHE ,handover);


    }
}
